
from flask import g
from werkzeug.utils import secure_filename
import os
import datetime
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif','PNG','JPG','JPEG','GIF'])

UPLOAD_FOLDER = 'G:/Work_server/Flask/learn-flask/static/upload'
def allowed_file(filename,allowen_extensions= ALLOWED_EXTENSIONS):
    return '.' in filename and \
        filename.rsplit('.', 1)[1] in allowen_extensions

# @app.route('/uploadfile', methods=['POST', 'GET'])
def do_upload(file=None,data=None,method='POST'):
    if method == 'POST':
        # 判断文件是否获取
        if not file:
            return False
        # 判断文件类型是否为 图片
        if not allowed_file(file.filename):
            return False
        #使用id保存对应的图片地址 所以判断一下
        if not data['id']:
            return False
        # 文件名=> 商品id+为了安全使用secure_filename()处理的文件名 
        filename = f'{data["id"]}-{secure_filename(file.filename)}'
        #保存路径UPLOAD_FOLDER使用的是绝对路径 替换了\为/
        path = os.path.join(UPLOAD_FOLDER,filename).replace('\\','/')
        # 保存文件 
        try:
            file.save(path)
        except:
            return False
        # 把文件地址保存到数据库中
        sql_str = f'UPDATE commodity SET url="{path}" WHERE id="{data["id"]}"'
        try:
            db_res = g.db.update(sql_str)
        except:
            return False
        # 
        print(db_res)
        if  not db_res:
            return False
        return path


       